#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

#define BACKLOG 5

int main(int argc, char *argv[]){//利用传参的方式来获取端口号和IP地址
	
	int sockfd;
	int newfd;
	int add;
	char buf[BUFSIZ] = {};
	struct sockaddr_in addr;

	if(argc < 3){
		fprintf(stderr, "%s<addr><port>\n", argv[0]);
		return 0;
	}

	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
		perror("socket");
		return 0;
	}
	addr.sin_family = AF_INET;
	addr.sin_port = htons( atoi(argv[2]) ); // 字节序转换函数 主机字节序 小端 --> 网络字节序 大端

	if(inet_aton(argv[1], &addr.sin_addr) == 0){
		fprintf(stderr, "Invalid address\n");
		return 0;
	}

	int flag = 1, len = sizeof(int);
	if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, len) == -1){
		perror("setsockopt");
		return 0;
	}//套接字设置 地址快速重用

	add = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
	if(add == -1){
		perror("bind");
		return 0;
	}

	if(listen(sockfd, BACKLOG) == -1){
		perror("listen");
		return(0);
	}

	if((newfd = accept(sockfd, NULL, NULL)) < 0){
		perror("accept");
		return 0;
	}
	while(1){
		memset(buf, 0, BUFSIZ);
		read(newfd, buf, BUFSIZ);
		printf("buf = %s\n", buf);
	}
	
	close(newfd);
	close(sockfd);

	return 0;
}
